{% extends 'base.html' %}
{% load staticfiles %}

{% block head %}
    <link rel="stylesheet"
          href="{% static 'AdminLTE/bower_components/datatables.net-bs/css/dataTables.bootstrap.min.css' %}">
    <!-- Select2 -->
    <link rel="stylesheet" href="{% static 'AdminLTE/bower_components/select2/dist/css/select2.min.css' %}">

    <style>
        /* dataTables列内容居中 */
        #celery_task > tbody > tr > td {
            text-align: center;
        }

        /* dataTables表头居中 */
        #celery_task > thead:first-child > tr:first-child > th {
            text-align: center;
        }

        .form-horizontal .form-group {
            margin-right: -200px;
        }
    </style>
    <link rel="stylesheet" href="{% static 'jquery-confirm/dist/jquery-confirm.min.css' %}">
{% endblock %}

{% block content %}

    <div class="row">
        <div class="col-sm-7 pull-left" style="margin-bottom: 3px; margin-top: 3px">
            <button class="btn btn-sm btn-success pull-left" data-toggle="modal" id="add-celery-task"
                    data-target="#CeleryTaskModal">
                <i class="fa fa-plus-square"></i>
                <span class="bigger-110">新增CELERY任务</span>
            </button>
        </div>
        <div class="col-xs-12">
            <!-- /.box -->
            <div class="box">
                <!-- dataTable -->
                <div class="box-body">
                    <table id="celery_task" class="table table-bordered table-striped">
                        <thead>
                        <tr>
                            <th>任务名称</th>
                            <th>任务函数</th>
                            <th>过期时间</th>
                            <th>任务状态</th>
                            <th>任务描述</th>
                            <th>操作</th>
                        </tr>
                        </thead>
                        <tbody>
                        {% for periodic_task in periodic_tasks %}
                            <tr>
                                <td>{{ periodic_task.name }}</td>
                                <td>{{ periodic_task.task }}</td>
                                <td>{{ periodic_task.expires|date:"Y-m-d H:i:s"|default:"永不过期" }}</td>
                                <td>
                                    {% if periodic_task.enabled %}
                                        <span class="badge bg-green">启用</span>
                                    {% else %}
                                        <span class="badge bg-red">禁用</span>
                                    {% endif %}
                                </td>
                                <td>{{ periodic_task.description }}</td>
                                <td>
                                    <button type="button" class="btn btn-success btn-xs modify" data-toggle="modal"
                                            data-id="{{ periodic_task.id }}"
                                            data-target="#CeleryTaskModal">详细/修改
                                    </button>
                                    <button type="button" class="btn btn-danger btn-xs delete"
                                            data-id="{{ periodic_task.id }}">
                                        删除
                                    </button>
                                </td>
                            </tr>
                        {% endfor %}
                        </tbody>
                    </table>
                </div>
                <!-- /.box-body -->
            </div>
            <!-- /.box -->

            <!-- CeleryTaskModal  -->
            <div class="modal fade" id="CeleryTaskModal" tabindex="-1" role="dialog"
                 aria-labelledby="CeleryTaskModalLabel"
                 aria-hidden="true">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
                                &times;
                            </button>
                            <h4 class="modal-title" id="CeleryTaskModalLabel">

                            </h4>
                        </div>
                        {% if perms.plan.add_periodictask and perms.plan.change_periodictask %}
                            <div class="modal-body">
                                <form id="celery_task_detail" class="main form-horizontal">
                                    <fieldset>
                                        <div class="form-group">
                                            <label for="name" class="col-sm-2 control-label">任务名称</label>
                                            <div class="col-sm-6">
                                                <input type="text" class="form-control" name="name" id="name" required/>
                                            </div>
                                        </div>

                                        <div class="form-group">
                                            <label for="task" class="col-sm-2 control-label">任务函数&nbsp;<span
                                                    data-toggle="tooltip"
                                                    title="若要添加其他任务函数，需要在plan应用下的tasks.py文件中添加"><i
                                                    class="fa fa-exclamation-circle"></i></span></label>
                                            <div class="col-sm-6">
                                                <select class="form-control select2" id="task" name="task"
                                                        style="width: 100%;">
                                                    {% for celery_task in celery_tasks %}
                                                        <option>{{ celery_task }}</option>
                                                    {% endfor %}
                                                </select>
                                            </div>
                                        </div>

                                        <div class="form-group">
                                            <label for="args" class="col-sm-2 control-label">参数(列表格式)</label>
                                            <div class="col-sm-6">
                                                <input type="text" class="form-control" name="args" id="args"
                                                       placeholder='["aa","bb"] 使用双引号'/>
                                            </div>
                                        </div>

                                        <div class="form-group">
                                            <label for="kwargs" class="col-sm-2 control-label">参数(字典格式)</label>
                                            <div class="col-sm-6">
                                                <input type="text" class="form-control" name="kwargs" id="kwargs"
                                                       placeholder='{"ip":"192.168.10.10"} 使用双引号'/>
                                            </div>
                                        </div>

                                        <div class="form-group">
                                            <label for="queue" class="col-sm-2 control-label">队列&nbsp;<span
                                                    data-toggle="tooltip"
                                                    title="若要添加其他任务队列，需要在celery.py定义新的队列"><i
                                                    class="fa fa-exclamation-circle"></i></span></label>
                                            <div class="col-sm-6">
                                                <select class="form-control select2" id="queue" name="queue"
                                                        style="width: 100%;">
                                                    {% for queue in queues %}
                                                        <option>{{ queue }}</option>
                                                    {% endfor %}
                                                </select>
                                            </div>
                                        </div>

                                        <div class="form-group">
                                            <label for="expires" class="col-sm-2 control-label">过期时间&nbsp;<span
                                                    data-toggle="tooltip"
                                                    title="格式：2018-10-10 10:10:10"><i
                                                    class="fa fa-exclamation-circle"></i></span></label>
                                            <div class="col-sm-6">
                                                <input type="datetime-local" class="form-control" name="expires"
                                                       id="expires">
                                            </div>
                                        </div>

                                        <div class="form-group">
                                            <label for="enabled" class="col-sm-2 control-label">任务状态</label>
                                            <div class="col-sm-6">
                                                <select class="form-control select2" id="enabled" name="enabled"
                                                        style="width: 100%;">
                                                    <option value="1">启用</option>
                                                    <option value="0">禁用</option>
                                                </select>
                                            </div>
                                        </div>

                                        <div class="form-group">
                                            <label for="crontab" class="col-sm-2 control-label">Crontab调度</label>
                                            <div class="col-sm-6">
                                                <select class="form-control select2" id="crontab" name="crontab"
                                                        style="width: 100%;">
                                                    <option value="">-----</option>
                                                    {% for crontab_schedule in crontab_schedules %}
                                                        <option value="{{ crontab_schedule.id }}">{{ crontab_schedule.minute }}&nbsp;&nbsp;{{ crontab_schedule.hour }}&nbsp;&nbsp;{{ crontab_schedule.day_of_month }}&nbsp;&nbsp;{{ crontab_schedule.month_of_year }}&nbsp;&nbsp;{{ crontab_schedule.day_of_week }}</option>
                                                    {% endfor %}
                                                </select>
                                            </div>
                                        </div>

                                        <p class="text-red">*crontab调度与interval调度选择其中一个即可</p>

                                        <div class="form-group">
                                            <label for="interval" class="col-sm-2 control-label">Interval调度</label>
                                            <div class="col-sm-6">
                                                <select class="form-control select2" id="interval" name="interval"
                                                        style="width: 100%;">
                                                    <option value="">-----</option>
                                                    {% for interval_schedule in interval_schedules %}
                                                        <option value="{{ interval_schedule.id }}">
                                                            间隔&nbsp;{{ interval_schedule.every }}&nbsp;
                                                            {% if interval_schedule.period == 'days' %}
                                                                天
                                                            {% elif interval_schedule.period == 'hours' %}
                                                                小时
                                                            {% elif interval_schedule.period == 'minutes' %}
                                                                分钟
                                                            {% elif interval_schedule.period == 'seconds' %}
                                                                秒
                                                            {% elif interval_schedule.period == 'microseconds' %}
                                                                毫秒
                                                            {% endif %}
                                                        </option>
                                                    {% endfor %}
                                                </select>
                                            </div>
                                        </div>

                                        <div class="form-group">
                                            <label for="description"
                                                   class="col-sm-2 control-label">任务描述</label>
                                            <div class="col-sm-6">
                                            <textarea class="form-control" name="description"
                                                      id="description"></textarea>
                                            </div>
                                        </div>

                                        <div class="space-24"></div>

                                    </fieldset>
                                </form>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                                <button type="button" class="btn btn-primary" data-dismiss="modal"
                                        id="celery_task_ops"></button>
                            </div>
                        {% else %}
                            <div class="modal-body">
                                抱歉！您没有此操作的权限！如有疑问，请联系管理员！
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-default" data-dismiss="modal">确认</button>
                            </div>
                        {% endif %}
                    </div><!-- /.modal-content -->
                </div><!-- /.modal -->
            </div>
        </div>
    </div>
    <!-- /.row -->

{% endblock %}


{% block js %}
    <!-- Select2 -->
    <script src="{% static 'AdminLTE/bower_components/select2/dist/js/select2.full.min.js' %}"></script>
    <!-- DataTables -->
    <script src="{% static 'AdminLTE/bower_components/datatables.net/js/jquery.dataTables.min.js' %}"></script>
    <script src="{% static 'AdminLTE/bower_components/datatables.net-bs/js/dataTables.bootstrap.min.js' %}"></script>

    <script src="{% static 'jquery-confirm/dist/jquery-confirm.min.js' %}"></script>
    <script src="{% static 'js/jquery-dateFormat.min.js' %}"></script>

    <script>
        $(function () {
            celery_task_table = $('#celery_task').DataTable({
                columnDefs: [{
                    'targets': [-1,],
                    'orderable': false
                }],
                "order": [[0, "asc"]]
            });

            // Initialize Select2 Elements
            $('.select2').select2()

            // 处理在modal中select2当选框无法搜索的问题
            $.fn.modal.Constructor.prototype.enforceFocus = function () {
            };

            $("[data-toggle='tooltip']").tooltip();
        });

        <!-- celery_task操作 -->
        let celery_task_tbody = $('#celery_task tbody');
        let celery_task_ops = $('#celery_task_ops');

        // 添加celery_task
        $('#add-celery-task').on('click', function () {
            $(".select2").val('').trigger('change');
            $('.modal-title').text('新增celery_task');
            celery_task_ops.text('添加');

            celery_task_ops.unbind('click').on('click', function () {
                if ($('#interval').val().length !== 0 && $('#crontab').val().length !== 0) {
                    celery_task_ops.removeAttr('data-dismiss');
                    $.alert({
                        title: 'Tips',
                        type: 'red',
                        content: 'interval与crontab不能同时选择！',
                    })
                } else {
                    celery_task_ops.attr('data-dismiss', 'modal');
                    let data = $('#celery_task_detail').serializeJson();
                    $.ajax({
                        url: '/api/periodic_task/',
                        type: 'POST',
                        data: JSON.stringify(data),
                        dataType: 'json',
                        contentType: "application/json",
                        success: function (res) {
                            let expires = res.expires === null ? '永不过期' : $.format.date(res.expires, "yyyy-MM-dd HH:mm:ss");
                            let enabled = res.enabled === true ? '<span class="badge bg-green">启用</span>' : '<span class="badge bg-red">禁用</span>';
                            celery_task_table.row.add([
                                res.name,
                                res.task,
                                expires,
                                enabled,
                                res.description,
                                `<button type="button" class="btn btn-success btn-xs modify" data-toggle="modal" data-id="${res.id}" data-target="#CeleryTaskModal">详细/修改</button> <button type="button" class="btn btn-danger btn-xs delete" data-id="${res.id}">删除</button>`
                            ]).draw();
                        },
                        error: function (response) {
                            $.alert({
                                title: 'Tips',
                                type: 'red',
                                content: response.responseText,
                            })
                        }
                    })
                }
            })
        });

        // 更新celery_task
        celery_task_tbody.on('click', '.modify', function () {
            let celery_task_id = $(this).attr('data-id');
            $('.modal-title').text('修改celery_task');
            celery_task_ops.text('确认修改');

            $.get('/api/periodic_task/' + celery_task_id + '/', function (data) {
                let expires = data.expires === null ? '' : data.expires.slice(0, 16);
                let enabled = data.enabled ? 1 : 0;
                $('#name').val(data.name);
                $('#task').val(data.task).trigger('change');
                $('#args').val(data.args);
                $('#kwargs').val(data.kwargs);
                $('#queue').val(data.queue).trigger('change');
                $('#expires').val(expires);
                $('#enabled').val(enabled).trigger('change');
                $('#crontab').val(data.crontab).trigger('change');
                $('#interval').val(data.interval).trigger('change');
                $('#description').val(data.description);
            });

            celery_task_ops.unbind('click').on('click', function () {
                if ($('#interval').val().length !== 0 && $('#crontab').val().length !== 0) {
                    celery_task_ops.removeAttr('data-dismiss');
                    $.alert({
                        title: 'Tips',
                        type: 'red',
                        content: 'interval与crontab不能同时选择！',
                    })
                } else {
                    celery_task_ops.attr('data-dismiss', 'modal');
                    let data = $('#celery_task_detail').serializeJson();
                    $.ajax({
                        url: '/api/periodic_task/' + celery_task_id + '/',
                        type: 'PUT',
                        data: JSON.stringify(data),
                        dataType: 'json',
                        contentType: "application/json",
                        success: function () {
                            window.location.reload()
                        },
                        error: function (response) {
                            $.alert({
                                title: 'Tips',
                                type: 'red',
                                content: response.responseText,
                            })
                        }
                    })
                }
            });
        });

        // 删除celery_task
        celery_task_tbody.on('click', '.delete', function () {
            {% if perms.plan.delete_periodictask %}
                let pk = $(this).attr('data-id');
                let tr_obj = $(this).parents('tr');
                $.confirm({
                    title: 'Tips',
                    content: '确定要删除这条记录么？',
                    type: 'red',
                    buttons: {
                        Ok: function () {
                            $.ajax({
                                url: '/api/periodic_task/' + pk + '/',
                                method: 'DELETE',
                                success: function () {
                                    celery_task_table.row(tr_obj).remove().draw();
                                },
                                error: function (data) {
                                    $.alert({
                                        title: 'Tips',
                                        type: 'red',
                                        content: '删除失败！' + data.responseText,
                                    })
                                }
                            })
                        },
                        Cancel: function () {
                            //
                        }
                    }
                });
            {% else %}
                $.alert({
                    title: 'Tips',
                    type: 'red',
                    content: '抱歉！您没有删除任务的权限！如有疑问，请联系管理员！',
                });
            {% endif %}
        });

        // 将数据JSON化
        (function ($) {
            $.fn.serializeJson = function () {
                let serializeObj = {};
                let array = this.serializeArray();
                $(array).each(function () {
                    if (serializeObj[this.name]) {
                        if ($.isArray(serializeObj[this.name])) {
                            serializeObj[this.name].push(this.value);
                        } else {
                            serializeObj[this.name] = [serializeObj[this.name], this.value];
                        }
                    } else {
                        if (this.name === 'expires' && this.value === "") {
                            serializeObj[this.name] = null;
                        } else {
                            serializeObj[this.name] = this.value;
                        }
                    }
                });
                return serializeObj;
            };
        })(jQuery);
    </script>

{% endblock %}

>